<template>
    <view class="auth">
        <up-form :model="form" :rules="rules" label-width="90px" ref="formRef">
            <view class="form_part">
                <up-form-item label="所属承运商" border-bottom>
                    <up-input border="none" v-model="relateEntCode" placeholder="请输入企业邀请码"></up-input>
                </up-form-item>
                <up-form-item label="当前手机号" prop="captainPhone" border-bottom>
                    <up-input type="number" border="none" v-model="form.captainPhone" placeholder="请输入当前手机号"></up-input>
                </up-form-item>
            </view>

            <view class="form_part">
                <ssection title="请上传本人有效身份证(必填)" line></ssection>
                <view class="file_box">
                    <view style="margin-right: 20px;">
                        <view class="image_part" style="padding: 10px;">
                            <image :src="images.idCardPic1" @click="uploadImage('idCardPic1', 0, 1)">
                            </image>
                        </view>
                        <view class="file_title">身份证正面</view>
                    </view>
                    <view>
                        <view class="image_part" style="padding: 10px;">
                            <image :src="images.idCardPic2" @click="uploadImage('idCardPic2', 0, 0)">
                            </image>
                        </view>
                        <view class="file_title">身份证反面</view>
                    </view>
                </view>
            </view>
            <view class="form_part">
                <up-form-item label="船长姓名" border-bottom prop="captainName">
                    <up-input border="none" v-model="form.captainName" placeholder="上传身份证,系统自动识别"></up-input>
                </up-form-item>
                <up-form-item label="身份证号" border-bottom prop="idCard">
                    <up-input border="none" v-model="form.idCard" placeholder="上传身份证,系统自动识别"></up-input>
                </up-form-item>
                <up-form-item label="开始时间" border-bottom prop="idStartDate" @click="showOrClose(1, 'idStartDate')">
                    <up-input border="none" v-model="form.idStartDate" placeholder="上传身份证,系统自动识别" disabled
                        disabledColor="#fff"></up-input>
                </up-form-item>
                <up-form-item label="结束时间" border-bottom prop="idEndDate" @click="showOrClose(1, 'idEndDate')">
                    <up-input border="none" v-model="form.idEndDate" placeholder="上传身份证,系统自动识别" disabled
                        disabledColor="#fff"></up-input>
                </up-form-item>
            </view>
            <view class="form_part">
                <ssection title="请上传本人适任证(必填)" line></ssection>
                <view class="file_box">
                    <view>
                        <view class="image_part">
                            <image :src="images.certificate" @click="uploadImage('certificate')"></image>
                        </view>
                        <view class="file_title">适任证正面</view>
                    </view>
                    <view>
                        <view class="image_part">
                            <image :src="images.certificate2" @click="uploadImage('certificate2')"></image>
                        </view>
                        <view class="file_title">适任证副面</view>
                    </view>
                </view>
            </view>
            <view class="form_part">
                <up-button type="primary" color="rgb(0,129,255)" customStyle="borderRadius:5px" @click="auth"
                    :loading="btnLoading" loadingText="正在认证">去认证</up-button>
            </view>
        </up-form>
    </view>
    <up-datetime-picker v-model="defaultDate" :show="selectDateShow" :minDate="0" :maxDate="32503651199000" mode="date"
        @cancel="showOrClose(0)" @confirm="confirmDate"></up-datetime-picker>
    <up-toast ref="uToastRef"></up-toast>
</template>

<script lang="ts" setup>
import {
    ref,
    reactive,
    onMounted
} from "vue"
import idCardPic1 from '@/static/images/mine/Portraitface.png'
import idCardPic2 from '@/static/images/mine/National.png'
import certificate from '@/static/images/mine/qualCertificate.png'
import ssection from "@/components/ssection.vue"
import {
    chooseImage,
    getImage,
    uploadFiles
} from '@/api/file'
import {
    getInfo,
    Entlist,
    toAuth,
    haslinkEnt,
    linkEnt
} from "@/api/captain"
import normalizeDate from '@/utils/dateFormat'


/* 数据 */
const uToastRef = ref<any>(null)
const selectDateShow = ref(false)
// 企业邀请码
const relateEntCode = ref('')
//表单
const formRef = ref<UniFormRef | null>(null)
// 表单数据
const form = reactive({
    captainName: '',
    captainPhone: '',
    idCard: '',
    idEndDate: '',
    idStartDate: '',

    idCardPic1: '',
    idCardPic2: '',
    certificate: '',
    certificate2: '',
})
// 验证规则
const rules = reactive({
    captainName: [{
        required: true,
        message: '姓名不能为空',
        trigger: ['blur', 'change']
    }],
    captainPhone: [{
        required: true,
        message: '手机号不能为空',
        trigger: ['blur', 'change']
    }, {
        pattern: /(^1[3-9][0-9]{9}$)/g,
        message: '手机格式错误',
        trigger: ['blur', 'change']
    }],
    'idCard': [{
        required: true,
        message: '身份证号不能为空',
        trigger: ['blur', 'change']
    }, {
        pattern: /(^\d{15}$)|(^\d{17}[\dxX]$)/g,
        message: '请输入正确的身份证号',
        trigger: ['blur', 'change']
    }],
    idStartDate: [{
        required: true,
        message: '开始时间不能为空',
        trigger: ['blur', 'change']
    }],
    idEndDate: [{
        required: true,
        message: '结束时间不能为空',
        trigger: ['blur', 'change']
    }]
})
// 是否有关联企业
const isHasEnt = ref(false)
// 图片
const images = reactive({
    idCardPic1,
    idCardPic2,
    certificate,
    certificate2: certificate
})
// 按钮
const btnLoading = ref(false)
const defaultDate = ref(Date.now())
const dateKey = ref<keyof typeof form>('idStartDate')



/* 函数 */
const formatDate = (date: string|number) => {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}` // 输出: 2023-05-20
}
// 选择时间
const confirmDate = (e: any) => {
    form[dateKey.value] = formatDate(e.value)
    showOrClose(0)
}
// 打开或者关闭时间选择
const showOrClose = (type: number, key?: keyof typeof form) => {
    // type 0 关闭 1 打开
    if (type === 0) {
        selectDateShow.value = false
    } else {
        if (key) {
            if (form[key]) {
                defaultDate.value = new Date(form[key]).getTime()
            } else {
                defaultDate.value = Date.now()
            }
            dateKey.value = key
            selectDateShow.value = true
        }
    }
}
// 获取用户信息
const getUserInfo = async () => {
    uToastRef.value.show({
        message: '加载中...',
        type: 'loading',
        duration: -1
    })
    let res = await getInfo()
    uToastRef.value.hide()
    if (res.success) {
        Object.assign(form, {
            ...res.data,
            idStartDate: normalizeDate(res.data.idStartDate, true),
            idEndDate: normalizeDate(res.data.idEndDate, true)
        })
        for (let key in images) {
            if (form[key as keyof typeof form]) {
                getImage(form[key as keyof typeof form]).then(res => {
                    images[key as keyof typeof images] = res.data
                })
            }
        }
    }
}
// 获取用户是否已关联企业
const getUserEnt = async () => {
    uToastRef.value.show({
        message: '加载中...',
        type: 'loading',
        duration: -1
    })
    let res = await Entlist({
        limit: 10
    })
    uToastRef.value.hide()
    if (res.success) {
        isHasEnt.value = res.data && res.data.length > 0
    }
}
// 上传图片
const uploadImage = async (type: keyof typeof form, licenseType = 9, cardType = 0) => {
    /* 上传图片 */
    chooseImage().then(async image => {
        uToastRef.value.show({
            message: '正在上传',
            type: 'loading',
            duration: -1
        })
        let res: any = await uploadFiles(image, {
            licenseType,
            cardType
        })
        uToastRef.value.hide()
        if (res.success) {
            images[type as keyof typeof images] = image
            let data = res.data
            form[type] = data.fileId

            let ret = data.certificateInfo
            let id_dic = {
                'name': 'captainName',
                'iDNumber': 'idCard',
            }
            if (type === 'idCardPic1') {
                for (let key in ret) {
                    if (Object.keys(id_dic).includes(key)) {
                        form[id_dic[key as keyof typeof id_dic] as keyof typeof form] = ret[key]
                    }
                }
            } else if (type === 'idCardPic2') {
                form.idStartDate = normalizeDate(ret.startDate)
                form.idEndDate = normalizeDate(ret.endDate)
            }
        }
    })
}
// 认证
const auth = async () => {
    let valid = await formRef.value?.validate()
    if (!valid) {
        uToastRef.value.show({
            message: '请完成表单',
            type: 'warning'
        })
        return
    }
    btnLoading.value = true
    if (isHasEnt.value) {
        // 已经关联了企业逻辑
        await afterEntCheck()
    } else {
        // 没有关联企业逻辑
        if (!relateEntCode.value) {
            uToastRef.value.show({
                message: '请先填写所属营运商邀请码',
                type: 'warning'
            })
            btnLoading.value = false
            return
        }
        uToastRef.value.show({
            message: '正在检测营运商',
            type: 'loading',
            duration: -1
        })
        // 查询结果是该邀请码的企业是否已经与用户关联api
        let isLink = await haslinkEnt(relateEntCode.value)
        uToastRef.value.hide()
        if (isLink.data) {
            // 查询结果是该邀请码的企业已经与用户关联
            await afterEntCheck()
        } else {
            // 查询结果是该邀请码的企业还没与用户关联
            uToastRef.value.show({
                message: '正在关联营运商',
                type: 'loading',
                duration: -1
            })
            // 用户关联企业api
            let res = await linkEnt(relateEntCode.value)
            uToastRef.value.hide()
            if (res.success) {
                await afterEntCheck()
            }
        }
    }
    btnLoading.value = false
}
// 已关联企业逻辑封装
const afterEntCheck = async () => {
    let obj = {
        ...form
    }
    if (obj.idEndDate === "长期") {
        obj.idEndDate = '2999-12-31'
    }
    uToastRef.value.show({
        message: '正在认证',
        type: 'loading',
        duration: -1
    })
    // 认证api
    let res = await toAuth(obj)
    uToastRef.value.hide()
    if (res.success) {
        // 成功回调
        uToastRef.value.show({
            message: '认证成功',
            type: 'success',
            position: 'top',
            complete() {
                let {
                    captainName,
                    idCard,
                    captainPhone
                } = form
                uni.navigateTo({
                    url: `/package_mine/pages/auth/videoAuth?info=${encodeURIComponent(JSON.stringify({ name: captainName, idCard, phoneNumber: captainPhone }))}`
                })
            }
        })
    }
}
// 初始化封装
const init = async () => {
    await getUserInfo()
    await getUserEnt()
}



/* 钩子 */
onMounted(() => {
    init()
})
</script>

<style lang="scss" scoped>
.auth {
    .form_part {
        background-color: #fff;
        padding: 10px;
        box-sizing: border-box;
        margin-bottom: 10px;

        .file_box {
            display: flex;
            padding: 0 10px;

            >view {
                flex: 1;
                margin-right: 10px;

                &:last-child {
                    margin-right: 0;
                }

                .image_part {
                    width: 100%;
                    aspect-ratio: 3 / 2;
                    border: 1px solid #ddd;
                    box-sizing: border-box;

                    >image {
                        width: inherit;
                        height: 100%;
                        display: block;
                    }
                }

                .file_title {
                    padding: 15px 0 5px;
                    font-size: 14px;
                    text-align: center;
                }
            }
        }

        .low_tip {
            color: rgb(64, 117, 247);
        }
    }
}
</style>